<!DOCTYPE html>
<html lang="zh_CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>文件浏览器</title>
    <link href="../css/bootstrap5.3.min.css" rel="stylesheet" type="text/css" />
    <script src="../js/jquery-3.6.0.min.js"></script>
    <style>
        .mymess{
            padding-left: 5px;
            left: 10px;
            top: 50px;
            position: fixed;
            border: 1px solid #e9c5c5;
            border-radius: 5px;
            text-align: center;
            padding: 10px;
            width: 350px;
            font-size: large;
            color: aliceblue;
            background-color: #000000;
            opacity: 1;
        }
    </style>
</head>
<body>
    <div class="container">
        <!--        header 头部导航栏-->
        <div id="my_header">      </div>
        <div class="pb-4 pt-4 bg-success">
            <h3 class="text-center fw-bold" >
                在线云盘
            </h3>
        </div>
        <div class="border border-info mb-2 mt-2" id="header">
            <div class="row">
                <div class="col-sm-7 mt-1">
                    <input class="form-control" type="file" name=upload id=upload /> 
                </div> 
                <div class="col-sm-5 mt-1">
                    --<button id=btnupload type="button" class="btn btn-primary" >上传</button> 
                | <button id=btnnewdir type="button" class="btn btn-secondary" >新建文件夹</button>
                </div>
            </div>  
            <div class="row mt-2 mb-2">
                <span class="col-auto">当前路径： </span>
                <span class="col-auto" id="path"></span>
            </div> 
        </div>
        <div id="content">

        </div>
        <div id="dialog"></div>
    </div>
    
</body>
<script src="../js/jquery-3.6.0.min.js"></script>
<script>
    // 加载头部
    $(function(){
        $("#my_header").load("../index_header.html");
    });
    // 信息展示函数
    function showmess(mess){
        let div = $("<div class=mymess>"+mess+"</div>");
        $("body").append(div);
        
        var intv = setInterval(()=>{
            let top = div.css("top");
            top = parseInt( top.split("px")[0]  );
            if( top > 500){
                div.remove();
                clearInterval(intv);
            }
            div.css("top", (top+5)+"px"  );
            div.css("opacity",  1-(top/(800.0))  );
        } ,17);
    }

    let pathArray = ['首页']; // 路径数组
    let storage=localStorage.getItem("path");
    if(storage){
        pathArray = storage.split("/");
        pathArray[0] = '首页';
    }
    // 获取当前路径，from pathArray
    function getPath(){
        let res="";
        for(let i=1; i < pathArray.length; i++){
            res+= "/" + pathArray[i]; 
        }
        return res;
    }
    // 判断后缀结尾，传参： aaa.png, ['.png', '.jpg']
    function isEnd(str, subfix_arr){
        if(subfix_arr.length){
            for(let i=0; i<subfix_arr.length; i++){
                str = str.toLowerCase();
                if(str.endsWith(subfix_arr[i])){
                    return true;
                }
            }
        }else{
            return false;
        }
    }
    // 解析后台的json 显示文件和文件夹
    function unpackDirs(dirArr){
        let res = "<ul>";
        for(let i=0; i<dirArr.length; i++){
            let item = dirArr[i];
            let row = "<li class='mt-2'>  ";
            if( item.isDir ){
                // 文件夹的话
                row += "<button  type=button class='opbtn btn btn-primary btn-sm' name=DDIIRR"+item.name + ">操作</button> "
                row += "<font color=#0000FF class=item name=dir >"+item.name+"</font>";
            }else {
                // 普通文件
                row += "<button  type=button class='opbtn btn btn-info btn-sm'  name="+item.name + ">操作</button> "
                row += "<font color=#ff8060 class=item name=file >"+item.name+"</font>";
            }
            row += "</li>"
            res += row;
        }
        res += "</ul>";
        $("#content").html(res);
        // item类，点击文件或者文件夹， 添加点击事件 
        $(".item").click(  (e)=>{
            // 如果是文件
            if($(e.target).attr("name")=="file"){
                let fn = $(e.target).text();
                console.log("fn=" + fn);
                if(isEnd(fn, [".mp4", ".mov"])){
                    let v_url = "video_player.html#path="+getPath()+"&name=" + fn;
                    window.open(v_url);
                }else if(isEnd(fn, [".png", ".jpg", ".jpeg", ".gif"])){
                    let i_url = "video?path="+getPath()+"&name=" + fn;
                    window.open(i_url);
                }else{
                    showmess("该文件无默认操作");
                }
            }
            //否则如果是文件夹，进入
            else
                enter( $(e.target).text()  );
        });
        // 操作按钮
        $(".opbtn").click((e)=>{
            opbtn_handler( $(e.target) );
        });

    }
    //init
    let path = getPath();
    $.get("ls?path="+path, (data, status, xhr)=>{
        if(status=="success" && (data = JSON.parse(data)) && data.code==20){
              unpackDirs(data.data);
        }else{
            console.log("失败：" + status);
            console.log(data);
            alert("出现错误！" + data)
        }
    });
    // 更新路径显示
    function updatePath(){
        let res="<span>/"
        for(let i=0; i<pathArray.length; i++){
            let row = "<a href=# class=navPath name=" + i +" >"
            let path = pathArray[i];
            row += path;
            row += "</a> / ";
            res += row;
        }
        res = res.substring(0, res.length-2);
        res += "</span>";
        $("#path").html(res);
        //添加点击事件
        $(".navPath").click((e)=>{
            let id = parseInt($(e.target).attr("name"));
            while( pathArray.length > id+1 )
                pathArray.pop();
                enter("");
        });
    }
    updatePath();
    // 进入和退出
    function enter(itemname){
        if(itemname != "")
            pathArray.push(itemname);
        let path = getPath();
        $.get("ls?path=" + path, (data, status, xhr)=>{
            if(status=="success" && (data = JSON.parse(data)) && data.code==20){
                unpackDirs(data.data);
                updatePath();
                localStorage.setItem("path", path);
            }else{
                console.log("error:");
                console.log(data);
                if(itemname != "")
                    pathArray.pop();
                alert("出现错误！" + data)
            }
        });
    }
    // opbtn 点击事件 DDIIRR开头是文件夹
    function opbtn_handler(btn){
        DIALOG_CALLBACK_FILENAME = btn.attr("name");
        let isDir = false;
        if(DIALOG_CALLBACK_FILENAME.indexOf("DDIIRR") == 0 ){
            DIALOG_CALLBACK_FILENAME=DIALOG_CALLBACK_FILENAME.substring(6);
            isDir = true;
            dialog("请选择对文件夹【"+ DIALOG_CALLBACK_FILENAME +"】的操作", isDir);
        }else{
            dialog("请选择对文件【"+ DIALOG_CALLBACK_FILENAME +"】的操作", isDir);
        }
        $("#dialog_input").val(DIALOG_CALLBACK_FILENAME);
    }
    // dialog
    $("#dialog").css("position", "absolute");
        $("#dialog").css("z-index", "10");
        $("#dialog").css("padding-left", "5px");
        $("#dialog").css("top", "100px");
        $("#dialog").css("left", "20px");
        $("#dialog").css("width", "400px");
        $("#dialog").css("height", "350px");
        $("#dialog").css("background-color", "#aa99dd");
    var DIALOG_FLAG = false;
    var DIALOG_CALLBACK_FILENAME = ""; // 当前文件名
    // 对话框的各个按钮
    function dialog(title, isDir ){
        console.log(title + ", " + isDir);
        let html="<h5>"+title+"</h5>";
        html += "<input id=dialog_input autocomplete=off /> ";
        html += "<button id=btnrename class='btn btn-primary btn-sm' >重命名</button> <br>";
        html += "<button id=btncancel class='btn btn-info btn-sm' >取消</button> -- ";
        if( ! isDir){
            html += "<button id=btndown class='btn btn-primary btn-sm' >下载</button> "; 
            // console.log("DIALOG_CALLBACK_FILENAME:" + DIALOG_CALLBACK_FILENAME) 
            html += "<button id=btnmove class='btn btn-primary btn-sm'>移动</button> ";
        } 
        html += "<button id=btnrm class='btn btn-danger btn-sm'>删除</button> ";
        html += "<div id=tmpdiv ></div> ";
        $("#dialog").html(html);
        $("#dialog").show();
        $("#btncancel").click((e)=>{
            $("#dialog").hide();
        });
        //重命名
        $("#btnrename").click((e)=>{
            if( ! DIALOG_CALLBACK_FILENAME ){
                showmess("DIALOG_CALLBACK_FILENAME 异常!");
                return;
            }
            let dialog_input =  $.trim( $("#dialog_input").val() );
            if(dialog_input  == '' ){
                showmess("dialog_input 为空!");
                return;
            }
            $.get("rename?path=" + getPath() + "&fn=" +DIALOG_CALLBACK_FILENAME+ "&newfn="+ dialog_input,
            (data, succ, xhr)=>{
                console.log(data);
                if(succ=="success" &&(data=JSON.parse(data))&& data.code==20){
                    enter("");
                }else{
                    showmess("重命名失败：" + data.mess);
                }
                
            });
            $("#dialog").hide();
        });
        // 下载
        $("#btndown").click((e)=>{
            if( ! DIALOG_CALLBACK_FILENAME ){
                showmess("DIALOG_CALLBACK_FILENAME 异常!");
                return;
            }
            let downURL = "down?path="+getPath()+"&name=" + DIALOG_CALLBACK_FILENAME;
            var $aa = $('<a>点击我下载</a>');  
            $aa.attr('href', downURL);  
            $aa.attr('target','_blank');
            //$("#tmpdiv").html("");
            //$("#tmpdiv").append($aa); 
            // $aa.click(()=>{$("#dialog").hide();});
            window.open(downURL);
            
        }); 
        // 移动
        $("#btnmove").click((e)=>{
            if( ! DIALOG_CALLBACK_FILENAME ){
                showmess("DIALOG_CALLBACK_FILENAME 异常!");
                return;
            }
            // console.log(getPath());
            var newpath = prompt("请输入新路径", getPath()); 
            if(newpath){
                let url = "move?path="+getPath()+"&fn="+DIALOG_CALLBACK_FILENAME+"&newpath="+newpath;
                console.log(url);
                $.get(url, 
                (data, succ, xhr)=>{
                    if(succ=="success" && (data = JSON.parse(data)) && data.code==20){
                        showmess("移动成功");
                        enter("");
                    }else{
                        showmess("移动失败，路径不存在");
                    }
                });
                $("#dialog").hide();
            }else{
                showmess("输入不能为空");
            }
            
        }); 
        // 删除
        $("#btnrm").click((e)=>{
            if( ! DIALOG_CALLBACK_FILENAME ){
                showmess("DIALOG_CALLBACK_FILENAME 异常!");
                return;
            }
            let choose = confirm("【慎重】确认要删除：" + DIALOG_CALLBACK_FILENAME);
            if( ! choose ){ $("#dialog").hide(); return;}
            $.get("rm?path="+getPath()+"&name=" + DIALOG_CALLBACK_FILENAME, 
            (data, succ, xhr)=>{
                if(succ=="success" && (data = JSON.parse(data)) && data.code==20){
                    showmess("删除成功");
                    enter("");
                }else{
                    showmess("删除失败");
                }
            });
            $("#dialog").hide();
        });
    }
    $("#dialog").hide();

    // 上传按钮
    $("#btnupload").click((e)=>{
        let formData = new FormData();
        formData.append("upload", $("#upload")[0].files[0]);
        formData.append("path",  getPath() );
        showmess("正在上传");
        $.ajax({
            url:"upload", 
            type: 'POST',
            data: formData,
            contentType: false,
            processData: false,
            success: (res)=>{
                console.log(res); 
                showmess("上传成功！");
                enter("");
            }
        });

    });
    // 新建文件夹
    $("#btnnewdir").click((e)=>{
        let name=prompt("输入文件夹名称:", '新建文件夹');
        if( name ){
            $.get("newdir?path="+getPath() + "&name="+ name,(data,succ,xhr)=>{
                if(succ=="success" && (data=JSON.parse(data)) && data.code==20){
                    enter("");
                    showmess("创建【"+name+"】成功");
                }else{
                    showmess("创建失败，请确认文件名没有非法字符");
                }
            });
        }
    });

</script>
</html>